package com.xpalive.config.spring.exceptionhandle;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@Slf4j
public class XBasicErrorController extends BasicErrorController {

    public XBasicErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    public XBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    public XBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties,
        List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    /**
     * @return org.springframework.http.ResponseEntity<java.util.Map < java.lang.String,
        * java.lang.Object>>
     * @Author Pan Weilong
     * @Description 处理传过来的异常(解决自定义全局异常捕获不到的问题)
     * @Date 17:16 2019/6/27
     * @Param [request]
     **/
    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
//        Map<String, Object> body = getErrorAttributes(request,
//            isIncludeStackTrace(request, MediaType.ALL));
        Map<String, Object> body = getErrorAttributes(request,
            getErrorAttributeOptions(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        String code = body.get("status").toString();
        String message = body.get("message").toString();
        String error = body.get("error").toString();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", StringUtils.defaultIfBlank(message, error));
        if (request.getAttribute("exception") != null) {
            map.put("exception", request.getAttribute("exception"));
        }
        log.error("error {}", body);
        return new ResponseEntity<>(map, status);
    }
}
